/**
 * @author luther.seven@gmail.com
 */

//search feed backend.joost.com/tolbiac/feed/search?q=string

var friendsXHR;
var frdBase = "www.joost.com"; // no 'http://' or trailing '/'
var frdFeed = "api/events/getwatchedbyfriends/"; // no preceeding '/'

var frdMain;
var frdResults;
var frdTitle;
var date;
var desc;
var frdThumb;
var frdPath;

var cursorPosition = 1;

var joostStorageUn = "JoostUn";
var joostUserId;

// Takes a definition document and populates the various DCTK controls
function handleFriendsResult(doc)
{
    // extract information with XPath
	
	frdMain = doc.evaluate("//ns1:feed/ns1:title", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;

	frdResults = doc.evaluate("count(//ns1:entry)", doc, NSResolver, XPathResult.ANY_TYPE, null).numberValue;
	
	frdTitle = new Array()
	for (var i = 1; i <= frdResults; i++){
		frdTitle[i] = doc.evaluate("//ns1:entry[" + i + "]/ns1:title", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
		}
	date = new Array()
	for (var i = 1; i <= frdResults; i++){
		date[i] = doc.evaluate("//ns1:entry[" + i + "]/ns1:updated", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
		}
	desc = new Array()
	for (var i = 1; i <= frdResults; i++){
		desc[i] = doc.evaluate("//ns1:entry[" + i + "]/ns1:content", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
		}
	frdPath = new Array()
	for (var i = 1; i <= frdResults; i++){
		frdPath[i] = doc.evaluate("//ns1:entry[" + i + "]/ns1:link/@href", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
		}
    
    var dctk = connected.toolkit;
	
	var frdTitleEdit = frdMain.split(" ");

	frdMainTitle = dctk.getElementById("frdMainTitle");
	frdMainTitle.text = username+"'s "+frdTitleEdit[0]+" Videos";
	
	connected.debug.print(frdTitle[1]);
	connected.debug.print(frdPath[1]);
	//connected.debug.print(desc[1]);

	createFrdItemList()
}

function onFriendsXHRStateChange()
{
    if (friendsXHR.readyState == 4)
    {
        if (friendsXHR.status == 200)
        {
            handleFriendsResult(friendsXHR.responseXML);
        }
    }
}

function startFriendsRequest()
{
    friendsXHR = new XMLHttpRequest();
    friendsXHR.onreadystatechange = onFriendsXHRStateChange;
    friendsXHR.open("GET", "http://"+frdBase+"/"+frdFeed+username+"?fmt=atom&count=100", true);
    friendsXHR.send(null);
}

function frdMainButtonHandler(e)
{
    switch(e.buttonId)
    {
       case dcKeyEvent.BUTTON_ID_BACK:
        {
            // navigate back
            onLoadFavorites();
        }
        break;

        case dcKeyEvent.BUTTON_ID_MENU:
        {
			showUserPopup();
        }
        break;

    }
}

function playMedia()
{
	var dctk = connected.toolkit;
	
	var height = connected.outputHeight;
	var width = connected.outputWidth;
	
	var params = connected.createPageDescriptor();
	params.uri = playUrl;
	params.pageType = dcIConnected.PT_HTML;
	if (width/height >= 16/9) {
		params.viewConstraints.addResolutionConstraint(640, 360); //16:9
	}
	else if (width/height <= 4/3) {
		params.viewConstraints.addResolutionConstraint(480, 360); //4:3
	}
	params.audioCapture = true;
	//params.htmlInputFocusMode = dcIPageDescriptor.FOCUS_MODE_OBJECT;
	// load the page
	connected.debug.print("Playing: "+playUrl);
	
	connected.debug.print("Height: "+connected.outputHeight);
	connected.debug.print("Width: "+connected.outputWidth);
	
	connected.loadFromPageDescriptor(params);
}

function frdSelected()
{
  cursorPosition = itemList.curSel;
  var videoId = frdPath[cursorPosition+1].split("/")
  playUrl = "http://www.joost.com/player/bin/joostPlayer.swf?video="+videoId[3]+"&referer=&mode=player";
  playMedia();
}

function createFrdItemList(){
	var item;
	var dctk = connected.toolkit;
	for (var i = 1; i <= frdResults; i++){
		frdThumb = desc[i].split('\"');
		item = itemList.addItem("id-0"+[i]);
    	item.text = frdTitle[i];
		item.img.src = frdThumb[7];
		item.showText = true;
	}
}

function onLoadFriends()
{
    var dctk = connected.toolkit;

    dctk.logicalWidth = 640;
    dctk.logicalHeight = 360;
    
    // create root panel
	var root = dctk.createPanelCtrl("root", true);
	root.width = 640;
	root.height = 360;

	root.backgroundStyle = dctkIElement.BACKGROUND_STYLE_IMAGE;
	root.backgroundImg.src = "joost-background.jpg";
	root.color.rgb = 0x333333;
	root.filled = true;
	root.onUnhandledKeyEvent = frdMainButtonHandler;
	dctk.rootPanel = root;
	
	var logo = dctk.createImageCtrl("logo", true);
	logo.setRect(540, 310, 630, 350);
	logo.img.src = "joost-logo.png";
	root.addChild(logo);
	
	var storageUn = connected.openStorage(joostStorageUn,true);
	username = storageUn.get(joostUserId);
	
	var frdMainTitle = dctk.createLabelCtrl("frdMainTitle", true);
    frdMainTitle.font = dctk.createFontByFacename("DIN-Bold", false, false);
    frdMainTitle.setRect(0, 310, 540, 350);
    frdMainTitle.textColor.rgb = 0xCCCCCC;
    frdMainTitle.fontSize = 20;
    frdMainTitle.align = dctkLabel.TS_CENTER;
	frdMainTitle.valign = dctkLabel.TS_MIDDLE;
    frdMainTitle.text = "Loading...";
    root.addChild(frdMainTitle);
	
	var menuTxt = dctk.createLabelCtrl("menuTxt", true);
    menuTxt.font = dctk.createFontByFacename("DIN-Bold", false, false);
    menuTxt.setRect(0, 8, 640, 28);
    menuTxt.textColor.rgb = 0xcccccc;
    menuTxt.fontSize = root.height/22;
    menuTxt.align = dctkLabel.TS_CENTER;
	menuTxt.valign = dctkLabel.TS_MIDDLE;
	menuTxt.text = "(press MENU to change login)";
    root.addChild(menuTxt);
	
	itemList = dctk.createThumbCtrl("itemList", true);
    itemList.setRect(20, 30, 610, 310);
	itemList.thumbHCount = 4;
    itemList.thumbVCount = 2;
	itemList.fontSize = 14;
	//itemList.frdThumbHGap = 0.08;
	itemList.spacing = 0;
	itemList.marquee = true;
    itemList.keyWrap = true;
	itemList.showPageIndicator = true;
	itemList.textColor.rgb = 0xcccccc;
	itemList.textSelColor.rgb = 0x000000;
	itemList.labelColor.rgb = 0x000000;
	itemList.labelSelColor.rgb = 0xCCCCCC;
	itemList.onSelect = frdSelected;
	root.addChild(itemList);
	
	if (username == "") {
		showUserPopup();
	}
	else if (username == null) {
		showUserPopup();
	}
	
	startFriendsRequest();
	
	//dctk.screenFade(1, 0, 0.5);
	
	//connected.toolkit.debug.drawElementOutline = true;
}

